package com.gome.ocean.service.scheduler;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gome.ocean.common.enums.State;
import com.gome.ocean.dao.model.datax.JobBO;
import com.gome.ocean.service.datax.JobService;
import com.gome.ocean.service.task.TransferJobTask;
import com.gome.ocean.service.zookeeper.client.ZkClient;

/**
 * 任务恢复
 * 
 * @author haqiaolong 2016年6月15日 下午3:55:00
 * @since 5.0.0
 */
@Component
public class TaskRecover implements InitializingBean, DisposableBean {

    private final Logger         LOG = LoggerFactory.getLogger(TaskRecover.class);

    @Autowired
    private JobService           jobService;

    @Autowired
    private SchedulerServiceBean schedulerServiceBean;
    @Autowired
    private ZkClient             zkClient;

    @Override
    public void destroy() throws Exception {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (zkClient.isLeader()) {
            List<JobBO> jobBOs = jobService.findAllJobList();
            if (!CollectionUtils.isEmpty(jobBOs)) {
                for (JobBO jobBO : jobBOs) {
                    // 如果是表达式任务并且任务状态不是暂停 恢复任务
                    if (jobBO.isCronJob() && State.PAUSE != State.getState(jobBO.getState())
                            && StringUtils.isNotEmpty(jobBO.getCronExpression())) {
                        if (schedulerServiceBean.checkExists(jobBO)) {
                            schedulerServiceBean.removeJob(jobBO);
                        }
                        schedulerServiceBean.addJob(jobBO, TransferJobTask.class);
                        LOG.info("task recover jobBO:" + jobBO);
                    }
                }
            }
            LOG.info("task recover is complate!");
        }
    }
}
